package com.zrrd.sort;

import java.util.Arrays;

public class InsertionSort {
    public void insertionSort(int[] arr) {
        int temp;
        for (int i = 1; i < arr.length; i++) {
            for (int j = i; j - 1 >= 0; j--) {
                if (arr[j] < arr[j - 1]) {
                    temp = arr[j];
                    arr[j] = arr[j - 1];
                    arr[j - 1] = temp;
                } else {
                    break;
                }
            }
        }
    }

    public int binarySearch(int[] array, int temp, int start, int end) {
        if (start > end) {
            return -start - 1;
        }
        int middle = (start + end) / 2;
        if (temp < array[middle]) {
            return binarySearch(array, temp, start, middle - 1);
        } else if (temp > array[middle]) {
            return binarySearch(array, temp, middle + 1, end);
        } else {
            return middle;
        }
    }

    public void insertionSortOptimized(int[] arr) {
        int temp;
        for (int i = 1; i < arr.length; i++) {
            int index = binarySearch(arr, arr[i], 0, i - 1);
            if (index < 0) {
                index = -(index + 1);
            }
            for (int j = i; j - 1 >= index; j--) {
                temp = arr[j];
                arr[j] = arr[j - 1];
                arr[j - 1] = temp;
            }
        }
    }

    public static void main(String[] args) {
        int[] arr = new int[]{4, 6, 7, 3, 2, 9, 1, 0, 5, 8};
        InsertionSort is = new InsertionSort();
        is.insertionSort(arr);
        System.out.println(Arrays.toString(arr));
    }
}
